package cn.smvc.task.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.springframework.stereotype.Repository;

import cn.smvc.common.dao.JDBCUtils;
import cn.smvc.common.utils.StringUtils;
import cn.smvc.task.dao.TTimedTaskDao;
import cn.smvc.task.entity.TTimedTask;

@Repository("tTimedTaskDao")
public class TTimedTaskDaoImpl implements TTimedTaskDao {
	/*
	 * 这两个是处理数据库表字段下划线的，
	 * 		与实体类中的属性对应（驼峰规则）
	 */
	BeanProcessor bean = new GenerousBeanProcessor();
	RowProcessor processor = new BasicRowProcessor(bean);
	BeanListHandler<TTimedTask> beanListHandler = new BeanListHandler<TTimedTask>(TTimedTask.class, processor);
	BeanHandler<TTimedTask> beanHandler = new BeanHandler<TTimedTask>(TTimedTask.class, processor);
	
	@Override
	public List<TTimedTask> findAll() throws SQLException {
		String sql = "select * from t_timed_task";
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		List<TTimedTask> list = null;
		list = queryRunner.query(sql, beanListHandler);
		return list;
	}

	@Override
	public List<TTimedTask> findAll(TTimedTask task) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public TTimedTask findOne(String id) throws SQLException {
		String sql = "select * from t_timed_task where id=?";
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		TTimedTask task = null;
		task = queryRunner.query(sql, beanHandler, id);
		return task;
	}

	@Override
	public int save(TTimedTask task) throws SQLException {
		// sql
		String sql = "insert into t_timed_task(id,task_class,task_class_type,task_name,task_group,task_cron,roll_flag,fun_run_flag,run_flag,swith_flag) values(?,?,?,?,?,?,?,?,?,?) ";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql, 
					task.getId(),
					task.getTaskClass(),
					task.getTaskClassType(),
					task.getTaskName(),
					task.getTaskGroup(),
					task.getTaskCron(),
					task.getRollFlag(),
					task.getFunRunFlag(),
					task.getRunFlag(),
					task.getSwithFlag());
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public int update(TTimedTask task) throws SQLException {
		// sql
		StringBuilder sql = new StringBuilder();
		sql
		.append("update t_timed_task set ")
		.append("task_class=?,")
		.append("task_name=?,")
		.append("task_group=?,")
		.append("task_cron=?,")
//		.append("last_execute_datetime=?,")
//		.append("next_execute_datetime=?,")
//		.append("last_execute_timestamp=?,")
//		.append("next_execute_timestamp=?,")
//		.append("run_flag=?,")
		.append("swith_flag=? ")
		.append("where id=?")
		;
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql.toString(), 
					task.getTaskClass(),
					task.getTaskName(),
					task.getTaskGroup(),
					task.getTaskCron(),
//					task.getLastExecuteDatetime(),
//					task.getNextExecuteDatetime(),
//					task.getLastExecuteTimestamp(),
//					task.getNextExecuteTimestamp(),
//					task.getRunFlag(),
					task.getSwithFlag(),
					task.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public int delete(String id) throws SQLException {
		//sql
		String sql = "delete from t_timed_task  where id=? ";
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql.toString(), id);
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public int count() throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select count(*) from t_timed_task";
		Integer count = queryRunner.query(sql, new ScalarHandler<Integer>());
		return count;
	}
	
	@Override
	public int count(String where) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		StringBuilder sql = new StringBuilder();
		sql
		.append("select count(*) from t_timed_task where ")
		.append(where);
		Long count = queryRunner.query(sql.toString(), new ScalarHandler<Long>());
		
		return count != null ? count.intValue() : 0;
	}

	@Override
	public int updateNextExecuteDatetime(String nextExecuteTimestamp, String nextExecuteDatetime, 
			String id) 
			throws SQLException {
		// sql
		StringBuilder sql = new StringBuilder();
		sql
		.append("update t_timed_task set ")
		.append("next_execute_timestamp=?, ")
		.append("next_execute_datetime=? ")
		.append("where id=?")
		;
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql.toString(), 
					nextExecuteTimestamp,
					nextExecuteDatetime,
					
					id);
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public int updateNextAndLastExecuteDatetime(
			String nextExecuteTimestamp, String nextExecuteDatetime,
			String lastExecuteTimestamp, String lastExecuteDatetime, String id) throws SQLException {
		// sql
		StringBuilder sql = new StringBuilder();
		sql
		.append("update t_timed_task set ")
		.append("next_execute_timestamp=?, ")
		.append("next_execute_datetime=?, ")
		.append("last_execute_timestamp=?, ")
		.append("last_execute_datetime=? ")
		.append("where id=?")
		;
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存信息
			result = queryRunner.update(JDBCUtils.getConnection(), 
					sql.toString(), 
					nextExecuteTimestamp,
					nextExecuteDatetime,
					lastExecuteTimestamp,
					lastExecuteDatetime, 
					id);
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}
		return result;
	}

	@Override
	public int updateAllRunFlag(String runFlag) throws SQLException {
		// sql
		String sql = "update t_timed_task set run_flag=? ";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		// 用queryRunner保存信息
		result = queryRunner.update(JDBCUtils.getConnection(), sql, runFlag);
		return result;
	}

	@Override
	public List<TTimedTask> findBySql(String sql) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		List<TTimedTask> list = null;
		list = queryRunner.query(sql, beanListHandler);
		return list;
	}

	@Override
	public List<TTimedTask> findByWhere(String where) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t_timed_task where ").append(where);
		List<TTimedTask> list = null;
		list = queryRunner.query(sb.toString(), beanListHandler);
		return list;
	}

	@Override
	public List<TTimedTask> findPage(String where, int page, int limit, String orderBy) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t_timed_task where ").append(where);
		if(StringUtils.isNotEmpty(orderBy)) {
			sb.append(" order by ").append(orderBy);
		}
		sb.append(" limit ").append((page - 1) * limit).append(", ").append(limit);
		List<TTimedTask> list = null;
		list = queryRunner.query(sb.toString(), beanListHandler);
		return list;
	}

	@Override
	public List<TTimedTask> findAllTaskGroup() throws SQLException {
		String sql = "select distinct task_group from t_timed_task";
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		List<TTimedTask> list = null;
		
		list = queryRunner.query(sql, beanListHandler);
		
		return list;
	}

	@Override
	public int updateRunFlag(String id, String runFlag) throws SQLException {
		// sql
		String sql = "update t_timed_task set run_flag=? where id=?";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		// 用queryRunner保存信息
		result = queryRunner.update(JDBCUtils.getConnection(), sql, runFlag, id);
		return result;
	}

	

}
